<template>
  <div class="app-container">
    <!-- 农户信息管理 -->
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80">
        <el-form-item label="名字" prop="farmerName">
          <el-input
            v-noSpace
            v-model="queryParams.farmerName"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleSeach()"
            placeholder="请输入名字"
          />
        </el-form-item>
        <el-form-item label="类型" prop="farmerType">
          <el-select
            v-model="queryParams.farmerType"
            placeholder="请输入类型"
            class="!w-[192px]"
            clearable
            @change="handleSeach()"
          >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSeach">搜索</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
          <el-button
            icon="Plus"
            type="success"
            @click="handleAdd({}, 'add')"
            v-hasPerm="'sys:farmerInformation:edit'"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
      <el-card shadow="never">
        <el-table
          v-loading="loading"
          show-overflow-tooltip
          :tooltip-formatter="tableRowFormatter"
          :data="tableData"
        >
          <el-table-column prop="farmerName" label="农户名称" />
          <el-table-column prop="farmerType" label="农户类型">
            <template #default="scope">
              <div>{{ typeFormat(scope.row.farmerType) }}</div>
            </template>
          </el-table-column>

          <el-table-column prop="contact" label="联系方式" />
          <el-table-column prop="location" label="地理位置" />
          <el-table-column prop="plantArea" label="种植面积" />
          <el-table-column prop="annualQty" label="年产量" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button
                size="small"
                link
                type="primary"
                @click.stop="handleAdd(scope.row, 'edit')"
                v-hasPerm="'sys:farmerInformation:edit'"
              >
                修改
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click.stop="handleAdd(scope.row, 'info')"
              >
                查看
              </el-button>
              <el-button
                size="small"
                type="danger"
                link
                @click.stop="handleDelete(scope.row, scope.$index)"
                v-hasPerm="'sys:farmerInformation:del'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleSeach"
        />
      </el-card>
      <el-dialog
        v-model="dialogVisible.visible"
        :title="dialogVisible.title"
        width="1000px"
        @close="handleClose"
      >
        <el-form
          ref="dialogFormRef"
          :disabled="dialogVisible.type == 'info' ? true : false"
          :model="dialogFormData"
          :rules="rules"
          label-width="120px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="农户名称" prop="farmerName">
                <el-input
                  v-noSpace
                  :maxlength="50"
                  v-model="dialogFormData.farmerName"
                  placeholder="请输入农户名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="农户类型" prop="farmerType">
                <el-select
                  v-model="dialogFormData.farmerType"
                  placeholder="请输入农户类型"
                  style="width: 250px"
                >
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contact">
                <el-input v-noSpace v-model="dialogFormData.contact" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地理位置" prop="location">
                <el-input
                  v-noSpace
                  :maxlength="100"
                  v-model="dialogFormData.location"
                  placeholder="请输入地理位置"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="种植面积" prop="plantArea">
                <el-input v-noSpace v-model="dialogFormData.plantArea" placeholder="请输入种植面积">
                  <template #append>亩</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年产量" prop="annualQty">
                <el-input v-noSpace v-model="dialogFormData.annualQty" placeholder="请输入年产量">
                  <template #append>吨</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="农作物" prop="crops">
                <el-input
                  v-noSpace
                  :maxlength="100"
                  v-model="dialogFormData.crops"
                  placeholder="请输入农作物用,号隔开"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24">
              <el-form-item label="合作情况" prop="cooperation">
                <el-input v-noSpace
                  v-model="dialogFormData.cooperation"
                  :maxlength="300"
                  :rows="4"
                  type="textarea"
                  placeholder="请输入合作情况"
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-noSpace
                  v-model="dialogFormData.remark"
                  :maxlength="300"
                  :rows="4"
                  type="textarea"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <span class="dialog-footer df flex justify-center">
                <el-button @click="dialogVisible.visible = false">取 消</el-button>
                <el-button v-debounce="handleSave" type="primary">提 交</el-button>
              </span>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  tableRowFormatter,
  validatePositiveInteger,
  validatePositiveIntegers,
} from "@/utils/index";
import { FormItemRule } from "element-plus/es";
import farmerInformationAPI, {
  FarmerInfo,
  seachQuery,
} from "@/api/farmerInformation/farmerInformation";
// import { tableRowFormatter, validatePositiveInteger } from "@/utils/index";
// 加载loading
const loading = ref(false);
// 分页总数
const total = ref(0);
// 搜索ref
const queryFormRef = ref(ElForm);
// 一级弹窗ref
const dialogFormRef = ref(ElForm);
//一级弹窗
const dialogVisible = reactive({ visible: false, title: "", type: "" });
//一级表单验证
const rules = reactive<Record<string, FormItemRule[]>>({
  farmerName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  type: [{ required: true, message: "请输入类型", trigger: "blur" }],
  annualQty: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  plantArea: [{ required: true, validator: validatePositiveIntegers, trigger: "blur" }],
  contact: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
});

const queryParams: seachQuery = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 类型
const typeList = ref([
  { label: "家庭农场", value: "0" },
  { label: "个体农户", value: "1" },
  { label: "潜在供应商", value: "2" },
]);
//类型格式化
const typeFormat = (val: number) => {
  return typeList.value.find((item: any) => item.value == val)?.label;
};
// 列表参数
const tableData = ref([]);
const dialogFormData: FarmerInfo = reactive({});
// 查询方法
const handleSeach = () => {
  loading.value = true;
  farmerInformationAPI
    .getFarmerList(queryParams)
    .then((data) => {
      // Object.assign(tableData, { ...data?.list });
      tableData.value = [...(data?.list as never)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
// 重置方法
const handleReset = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleSeach();
};
// 新增、修改、查看方法
const handleAdd = (row: any, type: any) => {
  dialogVisible.visible = true;
  dialogVisible.type = type;
  if (type === "add") {
    dialogVisible.title = "新增";
    delete dialogFormData.id;
  }
  if (type === "edit") {
    dialogVisible.title = "修改";
    let data = { ...row };
    nextTick(() => {
      Object.assign(dialogFormData, { ...data });
    });
  }
  if (type === "info") {
    dialogVisible.title = "查看";
    let data = { ...row };
    nextTick(() => {
      Object.assign(dialogFormData, { ...data });
    });
  }
};
// 删除操作
const handleDelete = (row: any, index: any) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // tableData.splice(index, 1);
      // ElMessage.success("删除成功");
      // loading.value = false;
      loading.value = true;
      farmerInformationAPI
        .delFarmer({ id: row.id })
        .then((data) => {
          ElMessage.success("删除成功");
          handleSeach();
        })
        .catch((error) => {
          loading.value = false;
          // ElMessage.error(`error`);
        });
    })
    .catch(() => {
      // loading.value = false;
    });
};
// 弹窗关闭
const handleClose = () => {
  dialogVisible.visible = false;
  dialogFormRef.value?.clearValidate();
  dialogFormRef.value?.resetFields();
};
// 保存操作
const handleSave = () => {
  // if (dialogVisible.type === "add") {
  //   dialogFormData.id = `HY${new Date().getTime()}`;
  //   tableData.push(JSON.parse(JSON.stringify(dialogFormData)));
  //   dialogVisible.visible = false;
  //   ElMessage.success("保存成功");
  // } else {
  //   const index = tableData.findIndex((item: any) => item.id === dialogFormData.id);
  //   if (index !== -1) {
  //     tableData.splice(index as any, 1, JSON.parse(JSON.stringify(dialogFormData)));
  //   }
  //   dialogVisible.visible = false;
  //   ElMessage.success("修改成功");
  // }
  loading.value = true;
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    // const apiCall =
    //   dialogVisible.type === "add" ? basketManagementAPI.add : basketManagementAPI.update;
    farmerInformationAPI
      .saveOrUpdateFarmer(dialogFormData)
      .then((data) => {
        loading.value = false;
        dialogVisible.visible = false;
        ElMessage.success("保存成功");
        handleSeach();
      })
      .catch((error) => {
        loading.value = false;
        // ElMessage.error(`error`);
      });
  });
};
onMounted(() => {
  handleSeach();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
